package com.liwenfeng.tcpandupd;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class LoginClient {
    Socket socket;
    Scanner scanner = new Scanner(System.in);

    public void start() throws IOException {
        socket = new Socket("127.0.0.1", 8888);
        while (true) {
            System.out.println("输入命令：");
            System.out.println("1.注册  2.登录  exit.退出");
            System.out.println("请选择：");
            String command = scanner.next();
            switch (command) {
                case "1" -> register();
                case "2" -> login();
                case "3", "exit" -> {
                    System.out.println("退出系统...");
                    socket.close();
                    return;
                }
            }
        }
    }

    private void login() throws IOException {
        System.out.println("------请输入登录信息--------");
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入密码：");
        String password = scanner.next();
        String msg = username + "=" + password + "=登录";
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        os.write(msg.getBytes());
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(len);
        System.out.println(new String(bytes, 0, len));
    }

    private void register() throws IOException {
        System.out.println("------请输入注册信息--------");
        System.out.println("请输入用户名：");
        String username = scanner.next();
        System.out.println("请输入密码：");
        String password = scanner.next();
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();
        String msg = username + "=" + password + "=注册";
        os.write(msg.getBytes());
        byte[] bytes = new byte[1024];
        int len = is.read(bytes);
        System.out.println(new String(bytes, 0, len));
    }

    public static void main(String[] args) {
        try {
            new LoginClient().start();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
